<template>
  <div class="p-2">
    <transition>
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="文件名" prop="fileName">
              <el-input v-model="queryParams.name" placeholder="请输入文件名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="创建时间">
              <el-date-picker v-model="queryParams.createTime" value-format="yyyy-MM-DD" type="date"
              placeholder="选择日期"></el-date-picker>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['iot:file:upload']" type="primary" plain icon="Upload"
              @click="handleFile">上传文件</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="ossList" :header-cell-class-name="handleHeaderClass" height="500">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="文件名" align="center" prop="name" />
        <el-table-column label="原名" align="center" prop="oldName" />
        <el-table-column label="文件大小（MB）" align="center" prop="fileSize" />
        <el-table-column label="文件后缀" align="center" prop="fileSuffix" />
        <el-table-column label="文件展示" align="center" prop="fileUrl">
          <template #default="scope">
            <video v-if="scope.row.fileSuffix == 'video/mp4'" type="video/mp4" autoplay
              style="width: 100px; height: 100px" :src="scope.row.fileUrl"></video>
            <el-image v-else style="width: 100px; height: 100px" :src="scope.row.fileUrl" fit="contain"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable="custom">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="上传人" align="center" prop="createByName" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- <el-tooltip content="下载" placement="top">
              <el-button v-hasPermi="['system:oss:download']" size="mini" type="text" icon="el-icon-edit-outline"
                @click="handleDownload(scope.row)">下载</el-button>
            </el-tooltip> -->
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['iot:file:remove']" link size="mini" type="text" icon="el-icon-delete"
                @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog :visible.sync="dialog.visible" :title="dialog.title" width="30%" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="文件">
          <el-upload class="upload-demo" drag :action="url" :file-list="form.fileList" :headers="header" multiple
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="setAddFile">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { list, addFile, deleteFile } from '@/api/file';
import ImagePreview from '@/components/ImagePreview/index.vue';
import { getToken } from '@/utils/auth';
import { re } from 'mathjs';
export default {
  components: { ImagePreview },
  data() {
    return {
      url: process.env.VUE_APP_BASE_API + '/iot/upload',
      header: {
        Authorization: 'Bearer ' + getToken(),
        clientid: process.env.VUE_APP_CLIENT_ID
      },
      ossList: [],
      imageUrl: "",
      showTable: true,
      buttonLoading: false,
      loading: false,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      type: 0,
      previewListResource: true,
      dateRangeCreateTime: ['', ''],
      dialog: {
        visible: false,
        title: '文件上传'
      },
      defaultSort: { prop: 'createTime', order: 'ascending' },
      ossFormRef: null,
      queryFormRef: null,
      initFormData: {
        file: undefined
      },
      form: {
        name: "",
        fileList: [],
        fileUrl: "",
        fileSuffix: "",
        oldName: "",
        fileSize: 0
      },
      totalFileSize: 0,
      totalFileSizeNew: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: "",
        createTime: ""
      },
      rules: {
        file: [{ required: true, message: '文件不能为空', trigger: 'blur' }]
      }
    };
  },
  mounted() {
    this.getList()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res, file)
      this.form.fileSize = Number(file.size / 1024 / 1024).toFixed(2)
      this.form.fileUrl = res.data.url
      this.form.oldName = res.data.originalFilename
      this.form.name = res.data.newFileName
      this.form.fileSuffix = file.raw.type
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      // console.log(Number(file.size / 1024 / 1024).toFixed(2))
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // console.log(localStorage.getItem("fileSize"))
      console.log(Number(this.totalFileSizeNew) + Number((file.size / 1024 / 1024).toFixed(2)))
      this.totalFileSizeNew = Number(this.totalFileSizeNew) + Number((file.size / 1024 / 1024).toFixed(2));
      const isSize =this.totalFileSizeNew < localStorage.getItem("fileSize")
      // if (!isLt2M) {
      //   // this.$message.error('上传大小不能超过 2MB!');
      // }
      if (!isSize) {
        this.$message.error('所剩空间不足');
        this.totalFileSizeNew = this.totalFileSize;
      }

      return isSize;
    },
    cancel() {
      this.dialog.visible = false
    },
    submitForm() { },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: "",
        createTime: ""
      }
      this.getList()
    },
    handleHeaderClass() { },
    handleFile() {
      this.dialog.visible = true
    },
    setAddFile() {
      console.log(this.form)
      if (this.form.fileList.length > 0) {
        this.$message({
          type: 'warning',
          message: '请单个上传!'
        });
        return;
      }
      addFile(this.form).then((res) => {
        this.$message({
          type: 'success',
          message: '上传成功!'
        });
        this.getList()
        this.dialog.visible = false
      });
    },
    getList() {
      list(this.queryParams).then((res) => {
        this.totalFileSize = 0
        this.ossList = res.rows
        for (let i in this.ossList) {
          this.totalFileSize = this.ossList[i].fileSize + this.totalFileSize
          this.totalFileSizeNew = this.ossList[i].fileSize + this.totalFileSizeNew
        }
        console.log(this.totalFileSize)
        this.total = res.total
      });
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFile(row.id).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList()
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleDownload(row) {
      var name = row.name;
      var url = row.fileUrl;
      var suffix = url.substring(url.lastIndexOf("."), url.length);
      const a = document.createElement('a')
      a.setAttribute('download', name + suffix)
      a.setAttribute('target', '_blank')
      a.setAttribute('href', url)
      a.click()
    }
  }
};
</script>
